<?php defined('SYSPATH') OR die('No direct access allowed.');

class New_Controller extends Template_Controller 
{
	public $template = 'new';
	public $content = 'new_content';

	public function __construct()
	{
		parent::__construct();
	}

	private function InitNewView()
	{
		$this->template->title = 'Welcome to Fitness!';
	}

	public function index()
	{
		$this->InitNewView();
		$this->new_user();
	}

	private function new_user()
	{
		$this->template->content->form = array
		(
			'email'     	=> '',
			'password'     	=> '',
			'password_confirm'	=> '',
			'accept_terms' => '',
		);
		$this->template->content->errors = $this->template->content->form;

		$authentic = new Auth;
		if ($authentic->logged_in())
		{
			url::redirect('');
		}

		if ($_POST)
		{
			$this->vertifyForm();
		}
	}

	private function vertifyForm()
	{
		$post = $this->input->post();
		$user = ORM::factory('user');
		if ($user->validate($post, TRUE))
		{
			if ($post['accept_terms'])
			{
				$user->email = $post['email']; 
				$user->password = $post['password']; 

				if ($user->add(ORM::factory('role', 'login')) AND $user->save()) 
				{
					// 邀请设置
					$cookie_invite = cookie::get('invite_id', NULL, true);
					print Kohana::debug($cookie_invite);
					print Kohana::debug($user->id);
					if ($cookie_invite AND $user->id != $cookie_invite)
					{
						$invite = ORM::factory('invite');
						$invite->user_id = $cookie_invite;
						$invite->invited_user_id = $user->id;
						print Kohana::debug($invite->as_array());
						if ($invite->save())
						{
							echo 'suc';
						}
						cookie::delete('invite_id');
					}
					
					// 使用获得的数据登录
					Auth::instance()->login($post['email'], $post['password']); 
	 
					// 跳转到其他页面       
					if ($requested_url = Session::instance()->get('requested_url', ''))
					{
						url::redirect($requested_url);
					}
					else
					{
						url::redirect();
					}
				}
			}
			else
			{
				$post->add_error('accept_terms', 'required');
			}
		}
		$this->template->content->form = arr::overwrite($this->template->content->form, $post->as_array());
 
		// 传递错误字段，并且我们需要创建一个错误信息文件
		// Kohana 通过 errors() 方法调用错误信息文件传递错误信息
		$this->template->content->errors = arr::overwrite($this->template->content->errors, $post->errors('form_error_messages'));
	
	}
}



